package com.prs.crm.action;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.dom4j.Element;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;

import com.opensymphony.xwork2.ActionSupport;
import com.prs.crm.domain.hr.Person;

public class XmlAction extends ActionSupport{
	private static final long serialVersionUID = 1L;

	private Document document;
	
	private List<Person> persons;
	
	public List<Person> getPersons() {
		return persons;
	}

	public void setPersons(List<Person> persons) {
		this.persons = persons;
	}

	public void setDocument(Document document) {
		this.document = document;
	}

	public Document getDocument() {
		return document;
	}
	
	@Action
	public String editTestPerson()
	{
		return SUCCESS;
	}
	
	@Action
	public String saveTestPerson()
	{
		System.out.println(persons.size());
		return SUCCESS;
	}
	
	@Action(value="xmldownload",results={@Result(name="success",type="xslt",params={"exposedValue","document","location","/WEB-INF/xml.xsl"})})
	public String execute() throws Exception
	{
		org.dom4j.Document dom4jDoc = new org.dom4j.dom.DOMDocumentFactory()
		.createDocument();
		Element root = dom4jDoc.addElement("root");
		root.addAttribute("prodType", "CPU");
		
		for (int i = 0; i < 10; i++) {
			root.addElement("model").addAttribute("name", String.valueOf(i));
		}
	document = (Document)dom4jDoc;
	HttpServletResponse response = ServletActionContext.getResponse();

    response.setContentType("text/xml;charset=UTF-8");

    response.setHeader("Cache-Control", "no-cache");
	       return SUCCESS;
	}
	public static org.w3c.dom.Document XmlString2W3cDom(String xml)    
	                   throws SAXException, IOException, ParserConfigurationException {    
	             byte[] byteArray = xml.getBytes("UTF-8");    
	             ByteArrayInputStream baos = new ByteArrayInputStream(byteArray);    
	             DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();    
	             org.w3c.dom.Document doc = factory.newDocumentBuilder().parse(baos);    
	             return doc;    
	       }    
	      
}
